

package top.continew.admin.question.manger.service.msg;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Builder;
import top.continew.admin.common.context.UserContextHolder;
import top.continew.admin.question.model.msg.MsgCustomer;
import top.continew.admin.question.model.msg.SysMsg;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Builder
public class MessageBean {
    private MessageTopic topic;
    private String message;
    private MessageType type;
    private String url;
    private String messageNo;
    private List<People> customerIds = new ArrayList<>();
    private People createBy;

    public MessageBean addCustomer(long id, long role) {
        People people = new People();
        people.setId(id);
        people.setRole(role);
        if (customerIds == null) {
            customerIds = new ArrayList<>();
        }
        this.customerIds.add(people);
        return this;
    }

    public void send() {
        if (this.customerIds.size() > 0) {
            /** 创建消息 */
            SysMsg message = new SysMsg();
            message.setMessage(this.message);
            message.setTopic(this.topic.topic);
            message.setTopicKey(String.valueOf(this.topic.topicKey));
            message.setType(String.valueOf(this.type.typeKey));
            message.setCreateby(UserContextHolder.getUserId());
            if (StrUtil.isEmpty(messageNo)) {
                messageNo = message.getTopicKey() + message.getType() + DateUtil
                    .format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandom().ints(10);
            }
            message.setMessageNo(messageNo);
            message.setUrl(this.url);
            message.insert();
            /** 发送消息 */
            MsgCustomer messageCustomer = new MsgCustomer();
            messageCustomer.setMessageId(message.getId());
            messageCustomer.setStatus(MessageStatus.SEND.status);
            this.customerIds.forEach(s -> {
                messageCustomer.setId(null);
                messageCustomer.setCustomerId(s.getId());
                messageCustomer.setCustomerRole(s.getRole());
                messageCustomer.setCreateby(message.getCreateby());
                messageCustomer.setCreateRole(message.getCreateRole());
                messageCustomer.insert();
            });
        }
    }
}
